<?php

/**

 * 工作计划
 * 
 * @access  public 
 * @author  zhangyingheng<zhang_yh@jsumt.com.cn> 
 */

namespace Index\Controller;

use Think\Controller;

class PlanController extends BaseController {

    public $webid;

    public function _initialize() {
        parent::_initialize();
        $this->title = '工作计划';

        //我的计划记录数
        $this->allCount = $this->planCount('2');

        //关注计划的记录数
        $this->followCount = $this->planCount('1');

        //取webId
//        $webid = session('webid');
//        if (!$webid) {
//            $webid = M('web')->where('webname="工作计划"')->getField('id');
//        }
        $webid = M('web')->where('webname="工作计划"')->getField('id');
        $this->webid = $webid;
    }

    public function index() {
        $this->savePlanPercent();

        //判断计划总进度是否为100%
        //获取进行中的计划条数
        $lists = $this->getPlanData(0);
        $count = count($lists);
        $this->planCount = $count;

        //获取已完成的计划条数
        $lists = $this->getPlanData(1);
        $count = count($lists);
        $this->finishCount = $count;



        //获取计划类型
        $planTypes = M('plan_type')->where('pid = 0')->order('TYPE_NO')->select();
        $this->userPercents = $this->userProcessDetail($planTypes); //个人按类型完成计划百分比(员工和公司领导)
        $this->leaderProcessDetail = $this->leaderProcessDetail($planTypes);    //公司领导获取所有部门总计划百分比
        //判断用户角色
        //公司领导
        $pMap['PRIV_NO'] = array('elt', 20);
        $privIds = M('user_priv')->where($pMap)->getField('user_priv', true);
        if (in_array(session('user_priv'), $privIds)) {
            //公司领导
            $userPriv = 'comLeader';
        } else {
            //部门领导
            $pMap['PRIV_NO'] = array('between', [30, 40]);
            $privIds = M('user_priv')->where($pMap)->getField('user_priv', true);
            if (in_array(session('user_priv'), $privIds)) {
                $userPriv = 'deptLeader';
            } else {
                $userPriv = 'user';
            }
        }
        $this->userPriv = $userPriv;
        $this->display();
    }

    /*
     * ajax获取部门领导个人及部门计划百分比
     */

    public function getDeptPlanPercent() {
        //获取个人计划进展
        $planTypes = M('plan_type')->where('pid = 0')->order('TYPE_NO')->select();
        $userPercents = $this->userProcessDetail($planTypes);
        foreach ($userPercents as $key => $row) {
            $return['type'][] = $row['name'];
            $return['userPercent'][] = $row['total'];
            $return['userNumber'][] = substr($row['total'], 0, -1);
        }

        //获取部门计划进展
        $deptPercents = $this->getDeptPercent();
        foreach ($deptPercents as $key => $row) {
            foreach ($userPercents as $u_key => $u_row) {
                if ($row['type'] == $u_row['name']) {
                    $return['deptPercent'][] = $row['total'];
                    $return['deptNumber'][] = substr($row['total'], 0, -1);
                }
            }
        }
        $return['name'] = ['个人进度', '部门进度'];
        $this->ajaxReturn($return);
    }

    //获取本部门计划分类进展
    private function getDeptPercent() {
        //获取公司领导部门id
        $leaderDeptId = M('department')->where('DEPT_NAME="公司领导"')->getField('dept_id');
        $dept_id = session('dept_id') == $leaderDeptId ? session('dept_id_other') : session('dept_id');
        //获取本部门所有员工
        $deptUsers = M('user')->where('DEPT_ID=' . $dept_id)->getField('user_id', true);
        if (!is_array($deptUsers)) {
            $deptUsers[] = $deptUsers;
        }

        $counts = M('plan_type')->where('pid = 0')->order('TYPE_NO')->select();
        foreach ($counts as $key => $row) {
            $map['TYPE'] = $row['type_id'];
            switch ($row['type_id']) {
                case 7:
                    $map['BEGIN_DATE'] = array('egt', date('Y-') . '01-01');
                    $map['END_DATE'] = array('elt', date('Y-') . '12-31`');
                    break;
                default:
                    $map['BEGIN_DATE'] = array('egt', date('Y-m-') . '01');
                    $map['END_DATE'] = array('elt', date('Y-m-') . '31`');
            }
            $data = array();
            foreach ($deptUsers as $u_key => $value) {
                $where['executor'] = array('like', '%' . $value . '%');
                $where['MANAGER'] = array('like', '%' . $value . '%');
                $where['PARTICIPATOR'] = array('like', '%' . $value . '%');
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
                $data[] = M('work_plan')->where($map)->order('BEGIN_DATE desc')->select();
            }
            $plans[$row['type_id']] = $this->array2D($data);
        }
        $deptPercent = $this->getPlanTypePercent($plans);
        return $deptPercent;
    }

    /*
     * 2018-3-14  公司领导需要看到各部门总计划完成百分比
     */

    private function leaderProcessDetail($planTypes) {
        //获取所有部门
        $depts = M('department')->where('DEPT_NAME != "公司领导"')->getField('dept_id', true);
        foreach ($depts as $key => $row) {
            $data = [];
            $users = M('user')->where('DEPT_ID=' . $row)->getField('user_id', true);
            if (!is_array($users)) {
                $users[] = $users;
            }

            $map['SMS_FLAG'] = 0;
            foreach ($users as $u_key => $u_row) {
                $where['executor'] = array('like', '%' . $u_row . '%');
                $where['MANAGER'] = array('like', '%' . $u_row . '%');
                $where['PARTICIPATOR'] = array('like', '%' . $u_row . '%');
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
                $data[$row][] = M('work_plan')->where($map)->order('BEGIN_DATE desc')->select();
            }
            $datas[$row] = $this->array2D($data[$row]);
        }
        //print_r($datas);
        $percent = $this->getPlanTypePercent($datas);
//        print_r($percent);
        return $percent;
    }

    //按分类计划总条数获取百分比
    private function getPlanTypePercent($datas) {
        foreach ($datas as $key => $row) {
            $total = $this->getPercent($row);
            $num = count($row) ? count($row) : 0;
            if ($row[0]) {
                $count = (round(($total / ($num * 100)), 2) * 100) . '%';
            } else {
                $count = '0%';
            }
            $percent[$key]['deptName'] = getDeptName($key);
            $percent[$key]['type'] = M('plan_type')->where('TYPE_ID=' . $key)->getField('type_name');
            $percent[$key]['count'] = $num;
            $percent[$key]['total'] = $count;
        }
        return $percent;
    }

    //列表
    public function lists() {
        //根据当前时间判断是否结束 2017-12-25改为通过进度百分比判断结束
//        $data = M('work_plan')->field('PLAN_ID,END_DATE')->where('SMS_FLAG = 0')->select();
//        foreach ($data as $key => $row) {
//            if ($row['end_date'] !== '0000-00-00' && ($row['end_date'] < date('Y-m-d H:i:s'))) {
//                $sData['SMS_FLAG'] = 1;
//                M('work_plan')->where('PLAN_ID=' . $row['plan_id'])->save($sData);
//            }
//        }
        //搜索
        $data = I('get.');
        if ($data['plantype']) {
            $map['TYPE'] = $data['plantype'];
            $this->planType = $data['plantype'];
        }
        if ($data['name']) {
            $where['NAME'] = array('like', '%' . $data['name'] . '%');
            $where['MANAGER'] = array('like', '%' . getUserId($data['name']) . '%');
            $where['executor'] = array('like', '%' . getUserId($data['name']) . '%');
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
            $this->name = $data['name'];
        }

        //获取计划类型
        $this->types = M('plan_type')->where('pid = 0')->order('type_no')->select();

        $limit = $this->limit;
        $lists = $this->getPlanData(I('get.type'), $limit, $map);
        $this->total = count($this->getPlanData(I('type'), 0));
        foreach ($lists as $key => $row) {
            if (getPlanMode($row['type']) == 0 && $row['is_mobile'] == 1) {
                $lists[$key]['sort'] = '<font color="' . getColorName($row['flag']) . '">' . msubstr($row['content'], 0, 14) . '（' . getPlanFlagName($row['flag']) . '）</font>';
            } else {
                //截取过长的计划名称
                $len = strlen($row['name']);
                if ($len > 54) {
                    $lists[$key]['sort'] = msubstr($row['name'], 0, 16);
                } else {
                    $lists[$key]['sort'] = $row['name'];
                }
            }

            //增加未读标记
            $readArr = explode(',', $row['reader']);
            if (!in_array(session('user_id'), $readArr) || empty($readArr)) {
                $lists[$key]['noRead'] = 1;
            } else {
                $lists[$key]['noRead'] = 0;
            }

            //获取负责人头像
            if (strpos($row['manager'], ',') !== false) {
                $row['manager'] = substr($row['manager'], 0, -1);
            }
            $lists[$key]['head'] = M('user')->where('USER_ID="' . $row['manager'] . '"')->getField('head');


            //负责人姓名
            $lists[$key]['manager'] = getChineseName(rtrim($row['manager'], ','));

            //获取关注信息，本人是否关注
            if ($row['follow_user']) {
                $gzs = explode(',', rtrim($row['follow_user'], ','));
                if (!is_array($gzs)) {
                    $gzs[] = $gzs;
                }
                $lists[$key]['gz'] = in_array(session('user_id'), $gzs) ? 1 : 0;
            }

            //获取最新动态信息
            $dMap['PLAN_ID'] = $row['plan_id'];
            $info = M('work_detail')->where($dMap)->order('write_time desc')->limit(1)->getField('progress');
            $len = strlen($info);
            if ($len > 60) {
                $lists[$key]['info'] = msubstr($row['name'], 0, 15);
            } else {
                $lists[$key]['info'] = $info;
            }
        }
//         print_r($lists);

        $this->lists = $lists;
        $this->is_end = I('type');
        $this->display();
    }

    /*
     * 获取计划列表
     * param $type  0进行中 1已完结 2关注 ''所有
     * param $limit 取几条，空取全部
     * return array
     */

    private function getPlanData($type = '', $limit = 0, $map = '') {
        $p = I('get.p', 1, 'intval');
        $start = $limit * ($p - 1);

        if (!$map) {
            $where['executor'] = array('like', '%' . session('user_id') . '%');
            $where['MANAGER'] = array('like', '%' . session('user_id') . '%');
            $where['PARTICIPATOR'] = array('like', '%' . session('user_id') . '%');
            $where['CREATOR'] = session('user_id');
            $where['TO_PERSON_ID'] = array('like', '%' . session('user_id') . '%');
            $where['OPINION_LEADER'] = array('like', '%' . session('user_id') . '%');
//            $where['TO_ID'] = array('like', '%' . session('dept_id') . '%');
//            $where['TO_ID'] = array('like', '%' . session('dept_id_other') . '%');
            $where['_string'] = ' TO_ID = "" OR TO_ID like "%' . session('dept_id') . '%"';
            if (session('dept_id_other')) {
                $where['_string'] = ' or TO_ID like "%' . session('dept_id_other') . '%" or TO_ID = ""';
            }
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        }
        if ($map[0] == 'all') {
            $map = '';
        }

        if ($type !== '') {
            if ($type == 1) {
                $map['SMS_FLAG'] = 1;
                $map['END_DATE'] = array('lt', date('Y-m-d'));
            } else {
                $map['SMS_FLAG'] = 0;
            }
        }

        if ($limit) {
            $lists = M('work_plan')->where($map)->order('level asc,END_DATE desc,BEGIN_DATE desc')->limit($start, $limit)->select();
        } else {
            $lists = M('work_plan')->where($map)->order('level asc,END_DATE desc,BEGIN_DATE desc')->select();
        }

//        echo M('work_plan')->_sql();die;
        foreach ($lists as $key => $row) {
            $lists[$key]['manager_name'] = getMoreUsername($row['manager']);
            $lists[$key]['participator_name'] = getMoreUsername($row['participator']);
            $lists[$key]['status'] = $row['sms_flag'] ? '<font color="red">已结束</font>' : '<font color="green">进行中</font>';
        }
        return $lists;
    }

    public function dropload() {
        $month = I('month') ? I('month') : '';
        $limit = $this->limit;
        if ($month) {
            $map['BEGIN_DATE'] = array('between', [$month . '-01', $month . '-31']);
        }

        //搜索
        if (I('get.plantype')) {
            $map['TYPE'] = I('plantype');
        }

        if (I('name')) {
            $where['NAME'] = array('like', '%' . I('name') . '%');
            $where['MANAGER'] = array('like', '%' . getUserId(I('name')) . '%');
            $where['executor'] = array('like', '%' . getUserId(I('name')) . '%');
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        }


        //当前用户角色排序号
//        $no = $this->privNo;
//
//        if ($no < 40) {
//            if ($no > 2) {
//                $where['TO_ID'] = array('like', '%' . session('dept_id') . '%');
//                $depts = array(explode(',', rtrim(session('dept_id_other'), ',')));
//                if (!empty($depts[0][0])) {
//                    foreach ($depts[0] as $key => $row) {
//                        $where['TO_ID'] = array('like', '%' . $row . '%');
//                    }
//                    $where['_logic'] = 'or';
//                    $map['_complex'] = $where;
//                } else {
//                    $map['TO_ID'] = $where['TO_ID'];
//                }
//            }
//        } else {
//            $where['MANAGER'] = array('like', '%' . session('user_id') . '%');
//            $where['PARTICIPATOR'] = array('like', '%' . session('user_id') . '%');
//            $where['CREATOR'] = session('user_id');
//            $where['TO_PERSON_ID'] = array('like', '%' . session('user_id') . '%');
//            $where['OPINION_LEADER'] = array('like', '%' . session('user_id') . '%');
////                $where['TO_ID'] = array('like', '%' . session('dept_id') . '%');
////                $where['TO_ID'] = array('like', '%' . session('dept_id_other') . '%');
//            $where['_logic'] = 'or';
//            $map['_complex'] = $where;
//        }
        $map = $this->getWhere($map);

        $lists = $this->getPlanData(I('get.type'), $limit, $map);
        foreach ($lists as $key => $row) {
            if (getPlanMode($row['type']) == 0 && $row['is_mobile'] == 1) {
                $lists[$key]['sort'] = '<font color="' . getColorName($row['flag']) . '">' . msubstr($row['content'], 0, 14) . '（' . getPlanFlagName($row['flag']) . '）</font>';
            } else {
                //截取过长的计划名称
                $len = strlen($row['name']);
                if ($len > 54) {
                    $lists[$key]['sort'] = msubstr($row['name'], 0, 18);
                } else {
                    $lists[$key]['sort'] = $row['name'];
                }
            }

            //增加未读标记
            $readArr = explode(',', $row['reader']);
            if (!in_array(session('user_id'), $readArr) || empty($readArr)) {
                $lists[$key]['noRead'] = 1;
            } else {
                $lists[$key]['noRead'] = 0;
            }

            //获取负责人头像
            if (strpos($row['manager'], ',') !== false) {
                $row['manager'] = substr($row['manager'], 0, -1);
            }
            $lists[$key]['head'] = M('user')->where('USER_ID="' . $row['manager'] . '"')->getField('head');

            //负责人姓名
            $lists[$key]['manager'] = getChineseName(rtrim($row['manager'], ','));

            //获取最新动态信息
            $dMap['PLAN_ID'] = $row['plan_id'];
            $info = M('work_detail')->where($dMap)->order('write_time desc')->limit(1)->getField('progress');
            $len = strlen($info);
            if ($len > 60) {
                $lists[$key]['info'] = msubstr($row['name'], 0, 20);
            } else {
                $lists[$key]['info'] = $info;
            }
        }
//        print_r($lists);

        $this->ajaxReturn($lists);
    }

    //工作计划查询
    public function search() {
        if (IS_POST) {
            $data = I('post.');
            if ($data['name'] != '') {
                $map['NAME'] = array('like', '%' . $data['name'] . '%');
            }
            if ($data['manager'] != '') {
                $map['MANAGER'] = getUserId($data['manager']);
            }
            if ($data['participator'] != '') {
                $map['PARTICIPATOR'] = array('like', '%' . getUserId($data['participator']) . '%');
            }
            if ($data['type']) {
                $map['_string'] = ' TYPE = ' . $data['type'] . ' or child_type = ' . $data['type'];
            }
            if (isset($data['sms_flag'])) {
                $map['SMS_FLAG'] = $data['sms_flag'];
            }
            if ($data['start'] != '') {
                $map['BEGIN_DATE'] = array('between', [$data['start'], $data['end']]);
            }

            /* 查询条件
             * admin\董事长\总经理可以查询全体
             * 部门负责人|公司领导查本部门
             */
            //当前用户角色排序号
            $no = $this->privNo;

            if ($no < 40) {
                if ($no > 2) {
                    $where['_string'] = ' TO_ID like "%' . session('dept_id') . '%" or TO_ID = ""';
                    $depts = array(explode(',', rtrim(session('dept_id_other'), ',')));
                    if (!empty($depts[0][0])) {
                        foreach ($depts[0] as $key => $row) {
//                            $where['TO_ID'] = array('like', '%' . $row . '%');
                            $where['_string'] = ' TO_ID like "%' . $row . '%" or TO_ID = ""';
                        }
                        $where['_logic'] = 'or';
                        $map['_complex'] = $where;
                    }
                }
            } else {
                $where['executor'] = array('like', '%' . session('user_id') . '%');
                $where['MANAGER'] = array('like', '%' . session('user_id') . '%');
                $where['PARTICIPATOR'] = array('like', '%' . session('user_id') . '%');
                $where['CREATOR'] = session('user_id');
                $where['TO_PERSON_ID'] = array('like', '%' . session('user_id') . '%');
                $where['OPINION_LEADER'] = array('like', '%' . session('user_id') . '%');
//                $where['TO_ID'] = array('like', '%' . session('dept_id') . '%');
//                $where['TO_ID'] = array('like', '%' . session('dept_id_other') . '%');
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
            }

            //保存条件到search表
            $sData['condition'] = json_encode($map);
            M('search')->where('id=1')->save($sData);

            $limit = $this->limit;
            //$limit = 2;
            $lists['lists'] = $this->getPlanData('', $limit, $map);
            $lists['total'] = count($this->getPlanData('', 0, $map));
            $this->ajaxReturn($lists);
        }

        //清空search表条件
        $sData['condition'] = '';
        M('search')->where('id=1')->save($sData);

        //获取计划类型
        $typeDatas = M('plan_type')->select();
        $this->types = getTree($typeDatas, 0);

        $this->display();
    }

    //查询条件
    private function getWhere($map) {
        //当前用户角色排序号
        $no = $this->privNo;

        if ($no < 40) {
            if ($no > 2) {
                $where['TO_ID'] = array('like', '%' . session('dept_id') . '%');
                $depts = array(explode(',', rtrim(session('dept_id_other'), ',')));
                if (!empty($depts[0][0])) {
                    foreach ($depts[0] as $key => $row) {
                        $where['TO_ID'] = array('like', '%' . $row . '%');
                    }
                    $where['_logic'] = 'or';
                    $map['_complex'] = $where;
                } else {
                    $map['TO_ID'] = $where['TO_ID'];
                }
            }
        } else {
            $where['executor'] = array('like', '%' . session('user_id') . '%');
            $where['MANAGER'] = array('like', '%' . session('user_id') . '%');
            $where['PARTICIPATOR'] = array('like', '%' . session('user_id') . '%');
            $where['CREATOR'] = session('user_id');
            $where['TO_PERSON_ID'] = array('like', '%' . session('user_id') . '%');
            $where['OPINION_LEADER'] = array('like', '%' . session('user_id') . '%');
//                $where['TO_ID'] = array('like', '%' . session('dept_id') . '%');
//                $where['TO_ID'] = array('like', '%' . session('dept_id_other') . '%');
            $where['_string'] = ' TO_ID = "" OR TO_ID like "%' . session('dept_id') . '%"';
            if (session('dept_id_other')) {
                $where['_string'] = ' or TO_ID like "%' . session('dept_id_other') . '%" or TO_ID = ""';
            }
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        }
        return $map;
    }

    //查询下拉加载
    public function droploadPlan() {
        //取条件
        $map = M('search')->where('id=1')->getField('condition');
        $where = json_decode($map, true);

        if ($where) {
            $limit = $this->limit;
            //$limit = 2;
            $lists['lists'] = $this->getPlanData('', $limit, $where);
            $lists['map'] = $map;
        } else {
            $lists['lists'] = '';
        }
        $this->ajaxReturn($lists);
    }

    public function show() {
        $id = I('id') ? I('id') : session('pcId');
        $map['PLAN_ID'] = $id;
        $info = M('work_plan')->where($map)->find();
        if($info['attach_type'] == 1)
            $info['attach_type_name'] = 'word';
        elseif($info['attach_type'] ==2)
            $info['attach_type_name'] = 'excel';
        elseif($info['attach_type'] ==3)
              $info['attach_type_name'] = 'ppt';  
        elseif($info['attach_type'] ==4)
            $info['attach_type_name'] = 'code';
        //增加已读标记
        if ($info['reader']) {
            $reader = $info['reader'] . ',' . session('user_id');
            $reader = array_unique(explode(',', $reader));
            $rData['reader'] = implode(',', $reader);
        } else {
            $rData['reader'] = session('user_id');
        }

        if ($info['executor']) {
            $info['name'] = $info['content'];
            $info['names'] = getMoreUsername($info['executor']);
        } else {
            $info['names'] = getMoreUsername($info['participator']);
        }

        M('work_plan')->where($map)->save($rData);

        /*
         * 进度和批注按时间顺序组成一个数组 2017-12-22 zyh
         */
        $info['detail'] = M('work_detail')->where($map)->order('WRITE_TIME DESC')->select();

        if ($info['detail']) {
            foreach ($info['detail'] as $key => $row) {
                $info['detail'][$key]['formatTime'] = strtotime($row['write_time']);
                $info['detail'][$key]['self'] = session('user_id');     //本人
                //判断当前进度中是否有附件
                if ($row['attachment_id'] || $row['uploads_url']) {
                    $info['detail'][$key]['file'] = 1;
                    $dUploads = downloadFile($row['attachment_id'], $row['attachment_name'], 'work_plan', $row['uploads'], $row['uploads_url']);
                    $picArr = ['png', 'jpg', 'jpeg', 'psd', 'bmp', 'gif'];
                    foreach ($dUploads as $d_key => $d_row) {
                        $ext = end(explode('.', $d_row['name']));
                        $dUploads[$d_key]['is_pic'] = in_array($ext, $picArr) ? 1 : 0;
                    }
                    $info['detail'][$key]['uploads'] = $dUploads;
                }
            }
        }

        //获取当前计划中参与人和负责人的进度
        $manager = explode(',', rtrim($info['manager'], ','));
        $participator = explode(',', rtrim($info['participator'], ','));
        $executor = explode(',', rtrim($info['executor'], ','));
        $users = array_merge($manager, $participator, $executor);
        $users = array_unique($users);

        $dMap['PLAN_ID'] = $id;
        foreach ($users as $key => $row) {
            if ($row['user']) {
                $progress[$key]['user'] = $row;
                $dMap['WRITER'] = $row;
                $percent = M('work_detail')->where($dMap)->max('percent');
                if (!$percent) {
                    $progress[$key]['percent'] = '0%';
                } else {
                    if ($percent > 100) {
                        $percent = 100;
                    }
                    $progress[$key]['percent'] = $percent . '%';
                }
            }
        }

        //总进度
        $num = 0;
        foreach ($progress as $key => $row) {
            $num += $row['percent'];
        }
        $total = $num / (count($progress) * 100);

        if ($total > 100) {
            $total = 100;
        } else {
            $total = intval($total * 100);
        }
        $this->total = $total;
        $this->plan = $info;
//        print_r($info);
        $this->sums = $progress;

        //获取PC端文件
        $ispc = 0;
        if ($info['attachment_name']) {
            $uploads = downloadFile($info['attachment_id'], $info['attachment_name'], 'work_plan', $info['uploads'], $info['uploads_url']);
            $ispc = 1;
        }
        if ($info['uploads_url']) {
            $names = explode(';', rtrim($info['uploads'], ';'));
            $urls = explode(';', rtrim($info['uploads_url'], ';'));
            for ($i = 0; $i < count($urls); $i++) {
                $tmpArr = [];
                if ($urls[$i]) {
                    if ($uploads) {
                        $tmpArr[$i]['name'] = $names[$i];
                        $tmpArr[$i]['url'] = $urls[$i];
                        array_push($uploads, $tmpArr);
                    } else {
                        $uploads[$i]['name'] = $names[$i];
                        $uploads[$i]['url'] = $urls[$i];
                    }
                }
            }
        }
        $picArr = ['png', 'jpg', 'jpeg', 'psd', 'bmp', 'gif'];
        foreach ($uploads as $key => $row) {
            $ext = end(explode('.', $row['name']));
            $uploads[$key]['is_pic'] = in_array($ext, $picArr) ? 1 : 0;
        }

        //判断用户是否有写进度日志的权限
        if (in_array(session('user_id'), $users)) {
            $is_write = 1;
        } else {
            $is_write = 0;
        }
        ////判断用户是否有编辑进度日志的权限
        $diaryCount = M('work_detail')->where('PLAN_ID = ' . $id . ' and WRITER like "%' . session('user_id') . '%"')->count();
        if ($diaryCount) {
            $is_edit = 1;
        } else {
            $is_edit = 0;
        }
        $this->is_write = $is_write;
        $this->is_edit = $is_edit;
        //计划中的附件
        $this->uploads = $uploads;

        //传部门id分类id,跳转回原页面 -> 当前计划show页面跳转
        $this->dept = I('get.dept');
        $this->cType = I('get.cType');
        $this->type = I('get.type') ? I('get.type') : '';    //存在表示关注页面
        //进行中、已完结show页面跳转
//        $this->type = I('get.type');
        //关注页面跳转
        if (I('type') == 'follow') {
            $this->type = I('type');
        }

        $this->display();
    }

    /*
     * 计算计划总进度并修改总进度字段
     * 原先通过判断负责人和参与人进度百分比计算总进度
     * 2018-1-11改为只判断负责人，负责人百分比为100时，总进度100，状态为1，否则0
     * @author   zhangyingheng
     */

    private function savePlanPercent() {
        //获取所有计划
        $plans = M('work_plan')->where('SMS_FLAG = 0')->select();
        $now = date('Y-m-d');
        foreach ($plans as $key => $row) {
            if ($row['total_percent'] == 100 || ($row['end_date'] < $now && ($row['end_date'] !== '0000-00-00'))) {
                //改状态sms_flag=1（总进度为100时或者结束日期存在并且小于当前时间时改为结束状态）
                $sData['SMS_FLAG'] = 1;
                M('work_plan')->where('PLAN_ID=' . $row['plan_id'])->save($sData);
            } else {
                $map['PLAN_ID'] = $row['plan_id'];
                if (getPlanMode($row['type']) == 0) {
                    //日计划
                    $count = count(explode(',', rtrim($row['executor'], ',')));
                    if ($count > 1) {
                        $write = explode(',', rtrim($row['executor'], ','));
                        $totalPercent = 0;
                        foreach ($write as $k_w => $k_v) {
                            $map['WRITER'] = array('like', '%' . $k_v . '%');
                            $totalPercent += M('work_detail')->where($map)->max('percent');
                        }
                        $percer = $totalPercent / (100 * $count) * 100;
                    } else {
                        $map['WRITER'] = rtrim($row['executor'], ',');
                        $percer = M('work_detail')->where($map)->max('percent');
                    }
                } else {
                    //详细
                    $count = count(explode(',', rtrim($row['manager'], ',')));
//                    if (getPlanMode($row['type']) == 0 && $row['is_mobile'] == 1 && $count > 1) {
                    if ($count > 1) {
                        $write = explode(',', rtrim($row['manager'], ','));
                        $totalPercent = 0;
                        foreach ($write as $k_w => $k_v) {
                            $map['WRITER'] = array('like', '%' . $k_v . '%');
                            $totalPercent += M('work_detail')->where($map)->max('percent');
                        }
                        $percer = $totalPercent / (100 * $count) * 100;
                    } else {
                        $map['WRITER'] = rtrim($row['manager'], ',');
                        $percer = M('work_detail')->where($map)->max('percent');
                    }
                }

                if ($percer >= 100) {
                    $sData['SMS_FLAG'] = 1;
                    $sData['total_percent'] = 100;
                } else {
                    $sData['SMS_FLAG'] = 0;
                    $sData['total_percent'] = $percer ? $percer : 0;
                }
                M('work_plan')->where('PLAN_ID=' . $row['plan_id'])->save($sData);
            }
        }
    }

    /*
     * 计算单个计划总进度
     * @author   zhangyingheng
     */

    private function saveOnePercent($plan_id) {
        $row = M('work_plan')->where('PLAN_ID=' . $plan_id)->find();

        $map['PLAN_ID'] = $row['plan_id'];
        if (getPlanMode($row['type']) == 0) {
            //日计划
            $count = count(explode(',', rtrim($row['executor'], ',')));
            if ($count > 1) {
                $write = explode(',', rtrim($row['executor'], ','));
                $totalPercent = 0;
                foreach ($write as $k_w => $k_v) {
                    $map['WRITER'] = array('like', '%' . $k_v . '%');
                    $totalPercent += M('work_detail')->where($map)->max('percent');
                }
                $percer = $totalPercent / (100 * $count) * 100;
            } else {
                $map['WRITER'] = rtrim($row['executor'], ',');
                $percer = M('work_detail')->where($map)->max('percent');
            }
        } else {
            //详细
            $count = count(explode(',', rtrim($row['manager'], ',')));

            if (getPlanMode($row['type']) == 0 && $row['is_mobile'] == 1 && $count > 1) {
                $write = explode(',', rtrim($row['manager'], ','));
                $totalPercent = 0;
                foreach ($write as $k_w => $k_v) {
                    $map['WRITER'] = array('like', '%' . $k_v . '%');
                    $totalPercent += M('work_detail')->where($map)->max('percent');
                }
                $percer = $totalPercent / (100 * $count) * 100;
            } else {
                $map['WRITER'] = rtrim($row['manager'], ',');
                $percer = M('work_detail')->where($map)->max('percent');
            }
        }

        if ($percer >= 100) {
            $sData['SMS_FLAG'] = 1;
            $sData['total_percent'] = 100;
        } else {
            $sData['SMS_FLAG'] = 0;
            $sData['total_percent'] = $percer ? $percer : 0;
        }

        M('work_plan')->where('PLAN_ID=' . $plan_id)->save($sData);
    }

    //计算计划总进度并修改总进度字段（原）
    private function savePlanPercent1() {
        //获取所有计划
        $plans = M('work_plan')->where('SMS_FLAG = 0')->select();
        $now = date('Y-m-d');
        foreach ($plans as $key => $row) {
            if ($row['total_percent'] == 100 || ($row['end_date'] <= $now && ($row['end_date'] !== '0000-00-00'))) {
                //改状态sms_flag=1（总进度为100时修改状态；PC端手机点结束时，end_date会改为结束时间，此时改状态）
                $sData['SMS_FLAG'] = 1;
                M('work_plan')->where('PLAN_ID=' . $row['plan_id'])->save($sData);
            } else {

                $manager = explode(',', rtrim($row['manager'], ','));
                $participator = explode(',', rtrim($row['participator'], ','));
                $users = array_merge($manager, $participator);
                $users = array_unique($users);
                foreach ($users as $u_key => $u_row) {
                    if ($u_row) {
                        $map['PLAN_ID'] = $row['plan_id'];
                        $map['WRITER'] = $u_row;
                        $tmp[$row['plan_id']][$u_row] = M('work_detail')->where($map)->max('percent');
                    }
                }

                //改状态sms_flag=0
                $sData['SMS_FLAG'] = 0;
            }
            M('work_plan')->where('PLAN_ID=' . $row['plan_id'])->save($sData);
        }
        //print_r($tmp);
        foreach ($tmp as $key => $row) {
            $total = array_sum($row);
            if ($total > 100) {
                $total = 100;
            }
            $pData['total_percent'] = round($total / (count($row) * 100), 2) * 100;
            $pMap['PLAN_ID'] = $key;
            M('work_plan')->where($pMap)->save($pData);
        }
    }

    //添加工作计划
    public function addPlan() {
        if (IS_AJAX) {
            $data = I('post.');
            
            //添加子分类
            if ($data['add_type']) {
                $tdata['TYPE_NAME'] = $data['add_type'];
                $tdata['TYPE_NO'] = 10;
                $tdata['mode'] = 1;
                $tdata['pid'] = $data['type'];
                $tdata['user_id'] = session('user_id');
                $pdata['child_type'] = M('plan_type')->add($tdata);
            } else {
                $pdata['child_type'] = $data['child_type'];
            }
            //添加work_plan表
            //判断是否为日计划
            if (getPlanMode($data['type']) == 0) {
                $pdata['NAME'] = $data['cont'];
                $pdata['CONTENT'] = $data['cont'];
                $pdata['executor'] = implode(',', $data['executor']);
                $pdata['flag'] = $data['flag'];
                $pdata['BEGIN_DATE'] = $data['begin_date'] ? $data['begin_date'] : date('Y-m-d');
                $pdata['END_DATE'] = $data['end_date'] ? $data['end_date'] : '0000-00-00';
                $pdata['is_mobile'] = 1;
                $pdata['attach_type'] = $data['s_attach_type'];
            } else {
                $pdata['NAME'] = $data['name'];
                $pdata['CONTENT'] = $data['content'];
                $pdata['MANAGER'] = implode(',', $data['manager']);
                $pdata['PARTICIPATOR'] = implode(',', $data['participator']);
                $pdata['BEGIN_DATE'] = $data['begin_date'] ? $data['begin_date'] : date('Y-m-d');
                $pdata['END_DATE'] = $data['end_date'] ? $data['end_date'] : '0000-00-00';
                $pdata['attach_type'] = $data['attach_type'];
            }
//            $pdata['child_type'] = $data['child_type'];
            $pdata['TYPE'] = $data['type'];
            $pdata['TO_ID'] = implode(',', $data['dept_ids']);
            $pdata['CREATOR'] = session('user_id');
            $pdata['CREATE_DATE'] = date('Y-m-d');
            $pdata['REMARK'] = $data['remark'];
            $pdata['TO_PERSON_ID'] = implode(',', $data['to_person_id']);
            $pdata['PUBLISH'] = 1;
            $pdata['OPINION_LEADER'] = implode(',', $data['opinion_leader']);
            $pdata['SMS_FLAG'] = 0;
            $pdata['level'] = $data['level'];
            $pdata['uploads'] = $data['uploads'];
            $pdata['uploads_url'] = $data['uploads_url'];
//            print_r($pdata);die;
            $res = M('work_plan')->add($pdata);
            if ($res) {
                $return['info'] = '添加成功';
                $return['url'] = U('allPlans');
            } else {
                $return['info'] = '添加失败';
            }
            $this->ajaxReturn($return);
        }

        $this->types = M('plan_type')->where('pid = 0')->order('TYPE_NO')->select();

        $this->display();
    }

    //获取地理位置
    private function getLocation($lat, $lng) {
//        $lat = 31.994293;
//        $lng = 118.715314;
        if ($lat == 32.0572355 && ($lng == 118.77807441)) {
            $location = '';
        } else {
            $coor = $lat . ',' . $lng;
            $url2 = 'http://api.map.baidu.com/geocoder/v2/?location=' . $coor . '&output=json&pois=1&ak=' . C('LOCATION_AK');
            $result2 = curl_post($url2, '', '', 0);
            $result2 = json_decode($result2, true);
            //$this->ajaxReturn($location);
            $location = $result2['result']['formatted_address'] . ' ' . $result2['result']['business'];
        }
        return $location;
    }

    //添加进度日志
    public function schedule() {
        if (IS_AJAX) {
            $data = I('post.');
//            print_r($data);die;
            $dData['PERCENT'] = $data['percent'];
            $dData['PROGRESS'] = $data['progress'];
            $dData['PLAN_ID'] = $data['plan_id'];
            $dData['WRITER'] = session('user_id');
            $dData['WRITE_TIME'] = date('Y-m-d H:i:s');
            $dData['TYPE_FLAG'] = 0;
            $dData['uploads'] = $data['uploads'];
            $dData['uploads_url'] = $data['uploads_url'];
            $dData['location'] = $this->getLocation($data['lat'], $data['lng']);
            $dData['is_diary'] = $data['is_diary'];
            $res = M('work_detail')->add($dData);

            if ($res && $data['is_diary']) {
                //写入工作日志
                $lData['USER_ID'] = session('user_id');
                $lData['DIA_TIME'] = date('Y-m-d H:i:s');
                $lData['DIA_DATE'] = date('Y-m-d H:i:s');
                $lData['DIA_TYPE'] = 1;
                $lData['SUBJECT'] = session('user_name') . date('Y-m-d') . '计划日志';
                $lData['CONTENT'] = $data['progress'];
                $lData['COMPRESS_CONTENT'] = '(BLOB)' . strlen($data['progress']) . '字节';
                $lData['IS_MOBILE'] = 1;
                $res = M('diary')->add($lData);
            }

            if ($res) {
                //添加阅读者字段（本人）,覆盖原有数据
                $rData['reader'] = session('user_id');
                M('work_plan')->where('PLAN_ID=' . $data['plan_id'])->save($rData);

                //修改总进度字段
                $this->saveOnePercent($data['plan_id']);

                //发送提示消息
                $map['PLAN_ID'] = $data['plan_id'];
                $row = M('work_plan')->where($map)->find();
                $content = "和您相关的工作计划《" . $row["name"] . "》新增了一条进度，填写人：" . getChineseName(session('user_id')) . "，填写时间：" . date("Y-m-d H:i:s") . "，<a href=\"http://www.jsumt.com:88/index.php/Index/Plan/show/id/" . $row['plan_id'] . "/webid/" . $this->webid . "\">点击查看</a>";

                //用户
                $manager = explode(',', $row['manager']);
                $paricipator = explode(',', $row['participator']);
                $creator = explode(',', $row['creator']);
                $person = explode(',', $row['to_person_id']);
                $leader = explode(',', $row['opinion_leader']);

                //部门 
                $deptUsers = getDeptUsers($row['to_id']);

                $users = array_merge($manager, $paricipator, $creator, $leader, $person, $deptUsers);
                $users = array_unique($users);
                setWeixinMsg($users, $content, $this->webid);

                $return['info'] = '添加成功';
                if (isset($_POST['is_end']) && I('post.is_end') != '') {
                    $return['url'] = U('lists', array('type' => I('is_end')));
                } else if (isset($_POST['is_follow']) && I('is_follow') == 'follow') {  //加关注参数，show页面返回关注列表
                    $return['url'] = U('show', array('id' => $data['plan_id'], 'dept' => $data['dept'], 'cType' => $data['cType'], 'type' => 'follow'));
                } else {
                    $return['url'] = U('show', array('id' => $data['plan_id'], 'dept' => $data['dept'], 'cType' => $data['cType']));
                }
            } else {
                $return['info'] = '添加失败';
            }
            $this->ajaxReturn($return);
        }

        $id = I('id');
        $plan = M('work_plan')->where('PLAN_ID=' . $id)->find();
        $map['PLAN_ID'] = $id;
        $map['WRITER'] = session('user_id');
        $map['TYPE_FLAG'] = 0;  //只显示进度
        $info = M('work_detail')->where($map)->select();
        $total = 0;
        foreach ($info as $key => $row) {
            if ($row['percent'] > $info[$key + 1]['percent']) {
                $total = $row['percent'];
            } else {
                $total = $info[$key + 1]['percent'];
            }
            //$total += $row['percent'];
        }
        $plan['total'] = $total;
        $plan['info'] = $info;

        $this->is_end = I('is_end');
        $this->plan_id = $id;
        $this->plan = $plan;

        //从当前计划详情页面中打开
        $this->dept = I('get.dept');
        $this->cType = I('get.cType');

        //加关注计划返回标记
        if (I('type') == 'follow') {
            $this->type = 'follow';
        }
        $this->display();
    }

    public function comment() {
        $id = I('post.id');
        $content = I('post.content');
        $lng = I('post.lng');
        $lat = I('post.lat');
        $data['PLAN_ID'] = $id;
        $data['WRITE_TIME'] = date('Y-m-d H:i:s');
        $data['PROGRESS'] = $content;
        $data['TYPE_FLAG'] = 1;
        $data['WRITER'] = session('user_id');
        $data['location'] = $this->getLocation($lat, $lng);
        $res = M('work_detail')->add($data);

        //添加批注提醒
        $map['PLAN_ID'] = $id;
        $row = M('work_plan')->where($map)->find();

        //用户
        $manager = $row['manager'] ? explode(',', $row['manager']) : [];
        $paricipator = $row['participator'] ? explode(',', $row['participator']) : [];
        $creator = $row['creator'] ? explode(',', $row['creator']) : [];
        $person = $row['to_person_id'] ? explode(',', $row['to_person_id']) : [];
        $leader = $row['opinion_leader'] ? explode(',', $row['opinion_leader']) : [];

        //部门 
        $deptUsers = $row['to_id'] ? getDeptUsers($row['to_id']) : [];

        $users = array_merge($manager, $paricipator, $creator, $leader, $person, $deptUsers);
        $users = array_unique($users);
        $content = '和您相关的工作计划《' . $row['name'] . '》新增了一条批注，<a href="http://www.jsumt.com:88/index.php/Index/Plan/show/id/' . $row['plan_id'] . '/webid/' . $this->webid . '">点击查看</a>';

        setWeixinMsg($users, $content, $this->webid);

        $return['status'] = $res !== false ? 1 : 0;
        if (isset($_POST['is_end']) && I('post.is_end') != 'undefined') {
            $return['url'] = $res !== false ? U('lists', array('type' => I('is_end'))) : '';
        } else {
            $return['url'] = $res !== false ? U('show', array('id' => I('post.id'), 'dept' => I('post.dept'), 'cType' => I('post.cType'))) : '';
        }

        $this->ajaxReturn($return);
    }

    //获取关注计划当前页面数据
    public function attentionPlan() {
        $map['FOLLOW_USER'] = array('like', '%' . session('user_id') . '%');

        //关注的周计划记录数
        $counts = M('plan_type')->where('pid = 0')->order('TYPE_NO')->select();
        foreach ($counts as $key => $row) {
            $map['TYPE'] = $row['type_id'];
            $counts[$key]['count'] = M('work_plan')->where($map)->count();
            if ($key == 0) {
                $weekPlan = M('work_plan')->where($map)->order('BEGIN_DATE desc')->select();
            }
        }
        if (I('is_follow') == 1 && isset($_POST['cType']) && $_POST['cType'] != '0') {//by qiao 2018.04.27
            $cType = I('post.cType');
            $map['TYPE'] = $cType;
            $allPlan = M('work_plan')->where($map)->order('BEGIN_DATE desc')->select();

            foreach ($allPlan as $k => $v) {
                if (getPlanMode($v['type']) == 0 && $v['is_mobile'] == 1) {
                    $allPlan[$k]['name'] = '<font color="' . getColorName($v['flag']) . '">' . msubstr($v['content'], 0, 16) . '（' . getPlanFlagName($v['flag']) . '）</font>';
                } else if ($v['type'] == 1) {
                    $allPlan[$k]['name'] = '<font color="' . getColorName($v['flag']) . '">' . msubstr(strip_tags($v['content']), 0, 16) . '（' . getPlanFlagName($v['flag']) . '）</font>';
                }

                //增加未读标记
                $readArr = explode(',', $v['reader']);
                if (!in_array(session('user_id'), $readArr) || empty($readArr)) {
                    $allPlan[$k]['noRead'] = 1;
                } else {
                    $allPlan[$k]['noRead'] = 0;
                }
                $allPlan[$k]['today'] = date('Y-m-d');
            }
        } else {
            //取全部计划
            $where['FOLLOW_USER'] = array('like', '%' . session('user_id') . '%');
            $allPlan = M('work_plan')->where($where)->order('BEGIN_DATE desc')->select();

            //取默认个人全部计划的数据
            foreach ($allPlan as $k => $v) {
                if (getPlanMode($v['type']) == 0 && $v['is_mobile'] == 1) {
                    $allPlan[$k]['name'] = '<font color="' . getColorName($v['flag']) . '">' . msubstr($v['content'], 0, 16) . '（' . getPlanFlagName($v['flag']) . '）</font>';
                } else if (getPlanMode($v['type']) == 0) {
                    $allPlan[$k]['name'] = '<font color="' . getColorName($v['flag']) . '">' . msubstr(strip_tags($v['content']), 0, 16) . '（' . getPlanFlagName($v['flag']) . '）</font>';
                }

                $con['PLAN_ID'] = $v['plan_id'];
                $con['WRITER'] = session('user_id');
                $process = M('work_detail')->where($con)->sum('PERCENT');
                $count = M('work_detail')->where($con)->count();
                $allPlan[$k]['percent'] = round($process / $count, 0);
                $allPlan[$k]['today'] = date('Y-m-d');
            }
        }

        $this->cType = $cType;
        $this->allPlan = $allPlan;
        $this->total = count($allPlan);
        $this->counts = $counts;
        $this->weekPlan = $weekPlan;
        $this->display();
    }

    //获取关注计划分类数据
    public function follow($para) {
        $map['FOLLOW_USER'] = array('like', '%' . session('user_id') . "%");
        if ($para) {
            $map['TYPE'] = $para;
        }

        $plan = M('work_plan')->where($map)->order('BEGIN_DATE desc')->select();

        foreach ($plan as $k => $v) {
            if (getPlanMode($v['type']) == 0 && $v['is_mobile'] == 1) {
                $plan[$k]['name'] = '<font color="' . getColorName($v['flag']) . '">' . msubstr($v['content'], 0, 16) . '（' . getPlanFlagName($v['flag']) . '）</font>';
            } else if ($v['type'] == 1) {
                $plan[$k]['name'] = '<font color="' . getColorName($v['flag']) . '">' . msubstr(strip_tags($v['content']), 0, 16) . '（' . getPlanFlagName($v['flag']) . '）</font>';
            }

            //增加未读标记
            $readArr = explode(',', $v['reader']);
            if (!in_array(session('user_id'), $readArr) || empty($readArr)) {
                $plan[$k]['noRead'] = 1;
            } else {
                $plan[$k]['noRead'] = 0;
            }
            $plan[$k]['today'] = date('Y-m-d');
        }

        $this->ajaxReturn($plan);
    }

    //全部计划
    public function allPlans() {
        $type = I('type');
        //取公司领导id
        $leaderId = M('department')->where('DEPT_NAME = "公司领导"')->getField('dept_id');

        if (session('dept_id') == $leaderId || session('user_id') == 'zhangyingheng' || session('user_id') == 'zhoulingling') {      //公司领导
            //除公司领导外所有部门
            $map['DEPT_NAME'] = array('neq', '公司领导');
            $dept = M('department')->where($map)->select();
            foreach ($dept as $k => $v) {
                $dept[$k]['dept_name'] = msubstr($v['dept_name'], 0, 4, 'utf-8', false);
            }

            $is_saff = 0;
            $cType = 0;
        } else {
            //取部门领导角色id
            $pMap['PRIV_NO'] = array('between', [30, 40]);
            $privIds = M('user_priv')->where($pMap)->getField('user_priv', true);
            if (in_array(session('user_priv'), $privIds)) {     //部门领导
                //取部门
                $dept = M('department')->where('DEPT_ID=' . session('dept_id'))->select();
                $is_saff = 0;
            } else {    //员工
                $is_saff = 1;
            }
        }

        //取进行中的周计划
        $map['SMS_FLAG'] = 0;
        $where['executor'] = array('like', '%' . session('user_id') . '%');
        $where['MANAGER'] = array('like', '%' . session('user_id') . '%');
        $where['PARTICIPATOR'] = array('like', '%' . session('user_id') . '%');
        $where['_logic'] = 'or';
        $map['_complex'] = $where;

        if (isset($_POST['dept'])) {
            $allPlan = $this->getAllPlansData(I('cType'), I('post.dept'));
            $this->deptStype = I('post.dept');
            $cType = I('post.cType');
            $counts = $this->getDeptPlanCount(I('dept'));
            $allNoRead = $counts[0]['allNoRead'] == 1 ? 1 : 0;
            $total = 0;
            foreach ($counts as $key => $row) {
                $total += $row['count'];
            }
        } else {
            $counts = M('plan_type')->where('pid = 0')->order('TYPE_NO')->select();
            $total = 0;
            foreach ($counts as $key => $row) {
                $map['TYPE'] = $row['type_id'];
                $counts[$key]['count'] = M('work_plan')->where($map)->count();

                //获取未读标记
                if ($counts[$key]['count']) {
                    $lists = M('work_plan')->field('PLAN_ID,TYPE,MANAGER,PARTICIPATOR,TO_ID,reader')->where($map)->select();
                    $allNoRead = 0;
                    $counts[$key]['noRead'] = getPlanTypeFlag($lists);
                    if ($counts[$key]['noRead'] == 1) {
                        $allNoRead = 1;  //如果未读标记的话，全部也为未读
                    }
                }
                $counts[$key]['sort'] = substr($row['type_name'], 0, -6);
                $total += $counts[$key]['count'];
            }
            $cType = 0;

            //取全部计划
            $allPlan = $this->getAllPlansData(0);

            //取默认个人全部计划的数据
            foreach ($allPlan as $k => $v) {
                if (getPlanMode($v['type']) == 0 && $v['is_mobile'] == 1) {
                    $allPlan[$k]['name'] = '<font color="' . getColorName($v['flag']) . '">' . msubstr($v['content'], 0, 16) . '（' . getPlanFlagName($v['flag']) . '）</font>';
                } else if (getPlanMode($v['type']) == 0) {
                    $allPlan[$k]['name'] = '<font color="' . getColorName($v['flag']) . '">' . msubstr(strip_tags($v['content']), 0, 16) . '（' . getPlanFlagName($v['flag']) . '）</font>';
                }

                //增加未读标记
                $readArr = explode(',', $v['reader']);
                if (!in_array(session('user_id'), $readArr) || empty($readArr)) {
                    $allPlan[$k]['noRead'] = 1;
                } else {
                    $allPlan[$k]['noRead'] = 0;
                }


                $con['PLAN_ID'] = $v['plan_id'];
                $con['WRITER'] = session('user_id');
                $process = M('work_detail')->where($con)->sum('PERCENT');
                $count = M('work_detail')->where($con)->count();
                $allPlan[$k]['percent'] = round($process / $count, 0);
                $allPlan[$k]['today'] = date('Y-m-d');
            }
        }

//        print_r($allPlan);
        $this->cType = $cType;
        $this->counts = $counts;
        $this->allNoRead = $allNoRead;  //全部未读计划标记
        $this->total = $total;  //全部个人计划个数
        $this->dept = $dept;
        $this->myself = session('user_id');
        $this->allPlan = $allPlan;

        $this->saff = $is_saff;
        $this->display();
    }

    public function allPlans1() {
        //除公司领导外所有部门
        $map['DEPT_NAME'] = array('neq', '公司领导');
        $dept = M('department')->where($map)->select();
        foreach ($dept as $k => $v) {
            $dept[$k]['dept_name'] = msubstr($v['dept_name'], 0, 4, 'utf-8', false);
        }

        //判断当前用户的查看权限
        //取公司领导id
        $leaderId = M('department')->where('DEPT_NAME = "公司领导"')->getField('dept_id');
        if (session('dept_id') == $leaderId) {
            //公司领导
            //取进行中的计划
            $map['SMS_FLAG'] = 0;
            $where['executor'] = array('like', '%' . session('user_id') . '%');
            $where['MANAGER'] = array('like', '%' . session('user_id') . '%');
            $where['PARTICIPATOR'] = array('like', '%' . session('user_id') . '%');
            $where['_logic'] = 'or';
            $map['_complex'] = $where;

            $counts = M('plan_type')->where('pid = 0')->order('TYPE_NO')->select();
            foreach ($counts as $key => $row) {
                $map['TYPE'] = $row['type_id'];
                $counts[$key]['count'] = M('work_plan')->where($map)->count();
                if ($key == 0) {
                    $weekPlan = M('work_plan')->where($map)->order('BEGIN_DATE desc')->select();
                }
            }

            //取默认周计划的数据
            foreach ($weekPlan as $k => $v) {
                // $weekPlan[$k]['name'] = mb_substr($v['name'], 0, 18);
                $con['PLAN_ID'] = $v['plan_id'];
                $con['WRITER'] = session('user_id');
                $process = M('work_detail')->where($con)->sum('PERCENT');
                $count = M('work_detail')->where($con)->count();
                $weekPlan[$k]['percent'] = round($process / $count, 0);
                $weekPlan[$k]['today'] = date('Y-m-d');
            }
            $cType = 0;

            if (isset($_POST['dept'])) {
                $weekPlan = $this->getAllPlansData(I('cType'), I('post.dept'));
                $this->deptStype = I('post.dept');
                $cType = I('post.cType');
                $counts = $this->getDeptPlanCount(I('dept'));
            }
        } else {
            //取部门领导角色id
            $pMap['PRIV_NO'] = array('between', [30, 40]);
            $privIds = M('user_priv')->where($pMap)->getField('user_priv', true);
            if (in_array(session('user_priv'), $privIds)) {
                //部门领导
                $dept = M('department')->where('DEPT_ID = ' . session('dept_id'))->select();
                $map['DEPT_ID'] = session('dept_id');
                $users = M('user')->where($map)->getField('user_id', true);
                if (!is_array($users)) {
                    $users[] = $users;
                }
                $map = array();
                //取进行中的计划
                $map['SMS_FLAG'] = 0;
                foreach ($users as $key => $value) {
                    $where['executor'] = array('like', '%' . $value . '%');
                    $where['MANAGER'] = array('like', '%' . $value . '%');
                    $where['PARTICIPATOR'] = array('like', '%' . $value . '%');
                    $where['_logic'] = 'or';
                    $map['_complex'] = $where;
                    $plan[] = M('work_plan')->where($map)->order('BEGIN_DATE desc')->select();
                }
                //$temp = $this->array2D($plan);
            } else {
                //员工
                //$map = array();
                //取进行中的计划
                $map['SMS_FLAG'] = 0;
                $where['executor'] = array('like', '%' . session('user_id') . '%');
                $where['MANAGER'] = array('like', '%' . session('user_id') . '%');
                $where['PARTICIPATOR'] = array('like', '%' . session('user_id') . '%');
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
                $is_saff = 1;
            }

            //$map = array();
            //取进行中的计划
            $map['SMS_FLAG'] = 0;
            $where['executor'] = array('like', '%' . session('user_id') . '%');
            $where['MANAGER'] = array('like', '%' . session('user_id') . '%');
            $where['PARTICIPATOR'] = array('like', '%' . session('user_id') . '%');
            $where['_logic'] = 'or';
            $map['_complex'] = $where;

            if (isset($_POST['dept'])) {
                $weekPlan = $this->getAllPlansData(I('cType'), I('post.dept'));
                $this->deptStype = I('post.dept');
                $cType = I('post.cType');
                $counts = $this->getDeptPlanCount(I('dept'));
            } else {
                $counts = M('plan_type')->where('pid = 0')->order('TYPE_NO')->select();
                foreach ($counts as $key => $row) {
                    $map['TYPE'] = $row['type_id'];
                    $counts[$key]['count'] = M('work_plan')->where($map)->count();
                    if ($key == 0) {
                        $weekPlan = M('work_plan')->where($map)->order('BEGIN_DATE desc')->select();
                    }
                }
                $cType = 0;
                //取默认周计划的数据
                foreach ($weekPlan as $k => $v) {
                    // $weekPlan[$k]['name'] = mb_substr($v['name'], 0, 18);
                    $con['PLAN_ID'] = $v['plan_id'];
                    $con['WRITER'] = session('user_id');
                    $process = M('work_detail')->where($con)->sum('PERCENT');
                    $count = M('work_detail')->where($con)->count();
                    $weekPlan[$k]['percent'] = round($process / $count, 0);
                    $weekPlan[$k]['today'] = date('Y-m-d');
                }
            }
        }
        // print_r($counts);
        $this->cType = $cType;
        $this->counts = $counts;
        $this->dept = $dept;
        $this->myself = session('user_id');
        $this->weekPlan = $weekPlan;

        $this->saff = $is_saff;
        $this->display();
    }

    public function allPlan() {
        $para = I('para');  //计划类型
        $dept_id = I('dept_id');  //部门
        $plans = $this->getAllPlansData($para, $dept_id);
        $this->ajaxReturn($plans);
    }

    //获取返回原页面的数据
    private function getAllPlansData($para, $dept_id = 0) {
//        echo $para,'-',$dept_id;
        //取进行中的计划
        $map['SMS_FLAG'] = 0;
        if ($para) {
            $map['TYPE'] = $para;
        }

        if ($dept_id) {
            //获取其他部门
            $users = M('user')->where('DEPT_ID=' . $dept_id)->getField('user_id', true);
            if (!is_array($users)) {
                $users[] = $users;
            }

            foreach ($users as $key => $value) {
                $where['executor'] = array('like', '%' . $value . '%');
                $where['MANAGER'] = array('like', '%' . $value . '%');
                $where['PARTICIPATOR'] = array('like', '%' . $value . '%');
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
                $plan[$value] = M('work_plan')->where($map)->order('level asc')->select();
            }

            $lists = $this->array2D($plan);
            unset($plan);
            $plan = [];
            foreach ($lists as $key => $row) {
                // $total += count($row);
                //排除执行人或参与人和创建人是同一个的情况下获取的数据
                if (($row['participator'] == session('user_id') || $row['executor'] == session('user_id')) && $row['creator'] == session('user_id')) {
                    unset($lists[$key]);
                } else {
                    array_push($plan, $row);
                }
            }
        } else {
            //获取本人的
            $where['executor'] = array('like', '%' . session('user_id') . '%');
            $where['MANAGER'] = array('like', '%' . session('user_id') . '%');
            $where['PARTICIPATOR'] = array('like', '%' . session('user_id') . '%');
            $where['_logic'] = 'or';
            $map['_complex'] = $where;

            $plan = M('work_plan')->field('PLAN_ID,NAME,CONTENT,TYPE,FOLLOW_USER,END_DATE,flag,total_percent,is_mobile,reader')->where($map)->order('level asc,END_DATE desc')->select();

            foreach ($plan as $k => $v) {
                $plan[$k]['today'] = date('Y-m-d');
            }
        }
        //及时计划加颜色
        foreach ($plan as $key => $row) {
            if (getPlanMode($row['type']) == 0 && $row['is_mobile'] == 1) {
                $plan[$key]['name'] = '<font color="' . getColorName($row['flag']) . '">' . msubstr($row['content'], 0, 16) . '（' . getPlanFlagName($row['flag']) . '）</font>';
            } else if (getPlanMode($row['type']) == 0) {
                $plan[$key]['name'] = '<font color="' . getColorName($row['flag']) . '">' . msubstr(strip_tags($row['content']), 0, 16) . '（' . getPlanFlagName($row['flag']) . '）</font>';
            }

            //增加未读标记
            $readArr = explode(',', $row['reader']);
            if (!in_array(session('user_id'), $readArr) || empty($readArr)) {
                $plan[$key]['noRead'] = 1;
            } else {
                $plan[$key]['noRead'] = 0;
            }
        }
        return $plan;
    }

    /*
     * 切换部门查看计划,默认显示选中部门的全部计划
     * param $para  int  部门Id
     */

    public function deptPlan($para) {
        $para = $para ? $para : I('para');
        //取进行中的计划
        $map['SMS_FLAG'] = 0;

        //获取计划分类
        $counts = M('plan_type')->where('pid = 0')->order('TYPE_NO')->select();

        if ($para) {
            $users = M('user')->where('DEPT_ID=' . $para)->getField('user_id', true);
            if (!is_array($users)) {
                $users[] = $users;
            }

            $total = 0;
            foreach ($counts as $key => $row) {
                $map['TYPE'] = $row['type_id'];
                $data = array();
                foreach ($users as $u_key => $value) {
                    $where['executor'] = array('like', '%' . $value . '%');
                    $where['MANAGER'] = array('like', '%' . $value . '%');
                    $where['PARTICIPATOR'] = array('like', '%' . $value . '%');
                    $where['_logic'] = 'or';
                    $map['_complex'] = $where;
                    $data[] = M('work_plan')->where($map)->order('BEGIN_DATE desc')->select();
                }

                $newdata = [];
                $tmp = $this->array2D($data);
                if (!empty($tmp)) {
                    foreach ($tmp as $t_key => $t_row) {
                        //排除参与人或执行人和创建人是同一个的情况下获取的数量
                        if (($t_row['participator'] == session('user_id') || $t_row['executor'] == session('user_id')) && $t_row['creator'] == session('user_id')) {
                            unset($tmp[$t_key]);
                        } else {
                            $newdata[] = $plans[] = $t_row;
                        }
                        $counts[$key]['data'] = $newdata;
                        $counts[$key]['count'] = count($newdata);
                        $counts[$key]['noRead'] = getPlanTypeFlag($newdata);
                    }
                } else {
                    $counts[$key]['data'] = [];
                    $counts[$key]['count'] = 0;
                }
                $total += $counts[$key]['count'];
            }
        } else {
            //个人
            $where['executor'] = array('like', '%' . session('user_id') . '%');
            $where['MANAGER'] = array('like', '%' . session('user_id') . '%');
            $where['PARTICIPATOR'] = array('like', '%' . session('user_id') . '%');
            $where['_logic'] = 'or';
            $map['_complex'] = $where;

            $total = 0;
            foreach ($counts as $key => $row) {
                $map['TYPE'] = $row['type_id'];
                $counts[$key]['count'] = M('work_plan')->where($map)->count();
                //获取未读标记
                if ($counts[$key]['count']) {
                    $lists = M('work_plan')->field('PLAN_ID,TYPE,MANAGER,PARTICIPATOR,TO_ID,reader')->where($map)->select();
                    $counts[$key]['noRead'] = getPlanTypeFlag($lists);
                    if ($counts[$key]['noRead'] == 1) {
                        $allNoRead = 1;  //如果未读标记的话，全部也为未读
                    }
                }
                $total += $counts[$key]['count'];
            }

            //获取个人所有计划
            unset($map['TYPE']);
            $plans = M('work_plan')->where($map)->select();
        }

        //及时计划加颜色
        foreach ($plans as $key => $row) {
            if (getPlanMode($row['type']) == 0 && $row['is_mobile'] == 1) {
                $plans[$key]['name'] = '<font color="' . getColorName($row['flag']) . '">' . msubstr($row['content'], 0, 16) . '（' . getPlanFlagName($row['flag']) . '）</font>';
            } else if (getPlanMode($row['type']) == 0) {
                $plans[$key]['name'] = '<font color="' . getColorName($row['flag']) . '">' . msubstr(strip_tags($row['content']), 0, 16) . '（' . getPlanFlagName($row['flag']) . '）</font>';
            }

            //增加未读标记
            $readArr = explode(',', $row['reader']);
            if (!in_array(session('user_id'), $readArr) || empty($readArr)) {
                $plans[$key]['noRead'] = 1;
            } else {
                $plans[$key]['noRead'] = 0;
            }
        }
//print_r($plans);die;
        $return['total'] = $total;
        $return['count'] = $counts;
        $return['plans'] = $plans;
        $return['allNoRead'] = $allNoRead;
        $this->ajaxReturn($return);
    }

    public function deptPlan1($para) {
        $para = $para ? $para : I('para');
        //取进行中的计划
        $map['SMS_FLAG'] = 0;
        if ($para) {
            $users = M('user')->where('DEPT_ID=' . $para)->getField('user_id', true);
            if (!is_array($users)) {
                $users[] = $users;
            }

            $map['TYPE'] = 1;
            //$map['BEGIN_DATE'] = array('between', [date('Y-m-') . '01', date('Y-m-') . '31']);
            foreach ($users as $key => $value) {
                //$value = substr($value, 0, -1);
                //$map['MANAGER|PARTICIPATOR'] = array(array('in', $value), array('like', '%' . $value . '%'), '_multi' => true);
                $where['executor'] = array('like', '%' . $value . '%');
                $where['MANAGER'] = array('like', '%' . $value . '%');
                $where['PARTICIPATOR'] = array('like', '%' . $value . '%');
                //$where['TO_ID'] = array('like','%'.$para.'%');
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
                $weekPlan[] = M('work_plan')->where($map)->order('BEGIN_DATE desc')->select();
            }
            $return['count']['weekCount'] = count($this->array2D($weekPlan));

            //部门月计划个数
            $map['TYPE'] = 2;
            //$map['BEGIN_DATE'] = array('between', [date('Y-m-') . '01', date('Y-m-') . '31']);
            foreach ($users as $key => $value) {
                //$value = substr($value, 0, -1);
                $where['executor'] = array('like', '%' . $value . '%');
                $where['MANAGER'] = array('like', '%' . $value . '%');
                $where['PARTICIPATOR'] = array('like', '%' . $value . '%');
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
                $monthPlan[] = M('work_plan')->where($map)->order('BEGIN_DATE desc')->select();
            }
            $return['count']['monthCount'] = count($this->array2D($monthPlan));

            $map['TYPE'] = 11;  //项目计划
            //$map['BEGIN_DATE'] = array('between', [date('Y-m-') . '01', date('Y-m-') . '31']);
            foreach ($users as $key => $value) {
                //$value = substr($value, 0, -1);
                $where['executor'] = array('like', '%' . $value . '%');
                $where['MANAGER'] = array('like', '%' . $value . '%');
                $where['PARTICIPATOR'] = array('like', '%' . $value . '%');
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
                $projectPlan[] = M('work_plan')->where($map)->order('BEGIN_DATE desc')->select();
            }
            $return['count']['projectCount'] = count($this->array2D($projectPlan));

            $map['TYPE'] = 7;   //年计划
            //$map['BEGIN_DATE'] = array('between', [date('Y-') . '01-01', date('Y-') . '12-31']);
            foreach ($users as $key => $value) {
                //$value = substr($value, 0, -1);
                $where['MANAGER'] = array('like', '%' . $value . '%');
                $where['PARTICIPATOR'] = array('like', '%' . $value . '%');
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
                $yearPlan[] = M('work_plan')->where($map)->order('BEGIN_DATE desc')->select();
            }
            $return['count']['yearCount'] = count($this->array2D($yearPlan));
            $return['weekPlan'] = $this->array2D($weekPlan);

            foreach ($return['weekPlan'] as $k => $v) {
                //$return['weekPlan'][$k]['name'] = mb_substr($v['name'], 0, 18);
                $con['PLAN_ID'] = $v['plan_id'];
                $con['WRITER'] = session('user_id');
                $process = M('work_detail')->where($con)->sum('PERCENT');
                $count = M('work_detail')->where($con)->count();
                $return['weekPlan'][$k]['percent'] = round($process / $count, 0);

                $attent = substr_count($v['follow_user'], session('user_id'));
                if ($attent) {
                    $return['weekPlan'][$k]['is_follow'] = 1;
                } else {
                    $return['weekPlan'][$k]['is_follow'] = 0;
                }
            }
        } else {
            //个人
            $where['executor'] = array('like', '%' . session('user_id') . '%');
            $where['MANAGER'] = array('like', '%' . session('user_id') . '%');
            $where['PARTICIPATOR'] = array('like', '%' . session('user_id') . '%');
            $where['_logic'] = 'or';
            $map['_complex'] = $where;

            //周计划
            $map['TYPE'] = 1;
            // $map['BEGIN_DATE'] = array('between', [date('Y-m-') . '01', date('Y-m-') . '31']);
            $weekPlan = M('work_plan')->where($map)->order('BEGIN_DATE desc')->select();
            $return['weekPlan'] = $weekPlan;
            $return['count']['weekCount'] = count($weekPlan);

            //月计划
            $map['TYPE'] = 2;
            $monthPlan = M('work_plan')->where($map)->order('BEGIN_DATE desc')->select();
            $return['monthPlan'] = $monthPlan;
            $return['count']['monthCount'] = count($monthPlan);

            //项目计划
            $map['TYPE'] = 11;  //项目计划
            $projectPlan = M('work_plan')->where($map)->select();
            $return['projectPlan'] = $projectPlan;
            $return['count']['projectCount'] = count($projectPlan);

            //年计划
            $map['TYPE'] = 7;   //年计划
            //$map['BEGIN_DATE'] = array('between', [date('Y-') . '01-01', date('Y-') . '12-31']);
            $yearPlan = M('work_plan')->where($map)->select();
            $return['yearPlan'] = $yearPlan;
            $return['count']['yearCount'] = count($yearPlan);
        }

        $this->ajaxReturn($return);
    }

    //获取各个部门计划数
    private function getDeptPlanCount($para = 0) {
        //取进行中的计划
        $map['SMS_FLAG'] = 0;
        if ($para) {
            $users = M('user')->where('DEPT_ID=' . $para)->getField('user_id', true);
            if (!is_array($users)) {
                $users[] = $users;
            }

            $counts = M('plan_type')->where('pid = 0')->order('TYPE_NO')->select();
            foreach ($counts as $key => $row) {
                $map['TYPE'] = $row['type_id'];
                $data = array();

                foreach ($users as $u_key => $value) {
                    $where['executor'] = array('like', '%' . $value . '%');
                    $where['MANAGER'] = array('like', '%' . $value . '%');
                    $where['PARTICIPATOR'] = array('like', '%' . $value . '%');
                    $where['_logic'] = 'or';
                    $map['_complex'] = $where;
                    $data[] = M('work_plan')->where($map)->order('BEGIN_DATE desc')->select();
                }

                $newdata = [];
                $tmp = $this->array2D($data);
                if (!empty($tmp)) {
                    foreach ($tmp as $t_key => $t_row) {
                        //排除参与人或执行人和创建人是同一个的情况下获取的数量
                        if (($t_row['participator'] == session('user_id') || $t_row['executor'] == session('user_id')) && $t_row['creator'] == session('user_id')) {
                            unset($tmp[$t_key]);
                        } else {
                            $newdata[] = $t_row;
                        }
                        $counts[$key]['data'] = $newdata;
                        $counts[$key]['count'] = count($newdata);
                        $counts[$key]['noRead'] = getPlanTypeFlag($newdata);
                    }
                } else {
                    $counts[$key]['data'] = [];
                    $counts[$key]['count'] = 0;
                }
            }
        } else {
            //个人
            $where['executor'] = array('like', '%' . session('user_id') . '%');
            $where['MANAGER'] = array('like', '%' . session('user_id') . '%');
            $where['PARTICIPATOR'] = array('like', '%' . session('user_id') . '%');
            $where['_logic'] = 'or';
            $map['_complex'] = $where;

            $counts = M('plan_type')->where('pid = 0')->order('TYPE_NO')->select();
            foreach ($counts as $key => $row) {
                $map['TYPE'] = $row['type_id'];
                $counts[$key]['count'] = M('work_plan')->where($map)->order('BEGIN_DATE desc')->count();
                //获取未读标记
                if ($counts[$key]['count']) {
                    $lists = M('work_plan')->field('PLAN_ID,TYPE,MANAGER,PARTICIPATOR,TO_ID,reader')->where($map)->select();
                    $counts[$key]['noRead'] = getPlanTypeFlag($lists);
                    if ($counts[$key]['noRead'] == 1) {
                        $counts[0]['allNoRead'] = 1;  //如果未读标记的话，全部也为未读
                    }
                }
            }
        }
        return $counts;
    }

    //二维数组去重
    public function array2D($tempPlan) {
        foreach ($tempPlan as $a => $b) {
            foreach ($b as $x => $y) {
                $plan[] = $y;
            }
        }
        $result = array();
        foreach ($plan as $key => $value) {
            $has = false;
            foreach ($result as $val) {
                if ($val['plan_id'] == $value['plan_id']) {
                    $has = true;
                    break;
                }
            }
            if (!$has)
                $result[] = $value;
        }
        foreach ($result as $key => $row) {
            $result[$key]['today'] = date('Y-m-d');
        }
        return $this->bubble($result);
    }

    //冒泡排序
    private function bubble($data) {
        $len = count($data);
        for ($i = 0; $i <= $len; $i++) {
            for ($j = 0; $j < $len - 1; $j++) {
                if ($data[$j]['begin_date'] < $data[$j + 1]['begin_date']) {
                    $tmp = $data[$j + 1];
                    $data[$j + 1] = $data[$j];
                    $data[$j] = $tmp;
                }
            }
        }
        return $data;
    }

    //关注计划
    public function attentPlan() {
        $type = I('type');
        $plan_id = I('plan_id');
        $map['PLAN_ID'] = $plan_id;
        $followUsers = M('work_plan')->field('FOLLOW_USER')->where($map)->getField('follow_user');

        $flag = 0;
        if ($followUsers) {
            $gzs = array_unique(explode(',', $followUsers));
            if (in_array(session('user_id'), $gzs)) {
                foreach ($gzs as $key => $row) {
                    if (session('user_id') == $row) {
                        unset($gzs[$key]);
                    }
                }
                $content['FOLLOW_USER'] = implode(',', $gzs);
                $flag = 1;
            } else {
                $content['FOLLOW_USER'] = $followUsers . session('user_id') . ",";
            }
        } else {
            $content['FOLLOW_USER'] = session('user_id') . ',';
        }

        $res = M('work_plan')->where($map)->save($content);
        if ($res !== false) {
            $return['status'] = 1;
            $return['msg'] = $flag == 1 ? '已取消' : '已关注';
        } else {
            $return = array('status' => 0, 'msg' => '操作失败');
        }

        $this->ajaxReturn($return);
    }

    //判断用户查看到的计划条数
    public function planCount($type) {
        if ($type == 1) {
            //关注的计划数
            $map['FOLLOW_USER'] = array('like', '%' . session('user_id') . "%");
            $plan = M('work_plan')->where($map)->count();
        } else {
            //全部计划
            //取进行中的当月计划,
            $map['SMS_FLAG'] = 0;
            //$map['_string'] = ' BEGIN_DATE between "' . date('Y-m-01') . '" and "' . date('Y-m-31') . '" or END_DATE between "' . date('Y-m-01') . '" and "' . date('Y-m-31') . '" or END_DATE = "0000-00-00"';
            $leaderId = M('department')->where('DEPT_NAME = "公司领导"')->getField('dept_id');
            if (session('dept_id') == $leaderId) {
                $counts = M('plan_type')->where('pid = 0')->order('TYPE_NO')->select();
                $plan = 0;
                foreach ($counts as $key => $row) {
                    $map['TYPE'] = $row['type_id'];
                    $plan += M('work_plan')->where($map)->count();
                }
            } else {
                //当前用户全部的周计划
                $where['executor'] = array('like', '%' . session('user_id') . '%');
                $where['MANAGER'] = array('like', '%' . session('user_id') . '%');
                $where['PARTICIPATOR'] = array('like', '%' . session('user_id') . '%');
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
                $plan = M('work_plan')->where($map)->count();
            }
        }
        return $plan;
    }

    public function planCount1($type) {
        if ($type == 1) {
            //关注的计划数
            $map['FOLLOW_USER'] = array('like', '%' . session('user_id') . "%");
            $plan = M('work_plan')->where($map)->count();
        } else {
            //全部计划
            //取进行中的计划
            $map['SMS_FLAG'] = 0;
            if (session('dept_id') == 141) {
                $map['TYPE'] = 1;
                // $map['BEGIN_DATE'] = array('between', [date('Y-m-') . '01', date('Y-m-') . '31']);
                $weekPlan = M('work_plan')->where($map)->select();
                foreach ($weekPlan as $k => $v) {
                    //$weekPlan[$k]['name'] = mb_substr($v['name'], 0, 18);
                    $con['PLAN_ID'] = $v['plan_id'];
                    $con['WRITER'] = session('user_id');
                    $process = M('work_detail')->where($con)->sum('PERCENT');
                    $count = M('work_detail')->where($con)->count();
                    $weekPlan[$k]['percent'] = round($process / $count, 0);
                }
                //当前用户全部的月计划记录数
                $map['TYPE'] = 2;
                //$map['BEGIN_DATE'] = array('between', [date('Y-m-') . '01', date('Y-m-') . '31']);
                $monthCount = M('work_plan')->where($map)->count();

                //当前用户全部的项目计划记录数
                $map['TYPE'] = 11;
                // $map['BEGIN_DATE'] = array('between', [date('Y-m-') . '01', date('Y-m-') . '31']);
                $projectCount = M('work_plan')->where($map)->count();

                //当前用户全部的年计划记录数
                $map['TYPE'] = 7;
                // $map['BEGIN_DATE'] = array('between', [date('Y-') . '01-01', date('Y-') . '12-31']);
                $yearCount = M('work_plan')->where($map)->count();
            } else {
                //当前用户全部的周计划
                $where['MANAGER'] = array('like', '%' . session('user_id') . '%');
                $where['PARTICIPATOR'] = array('like', '%' . session('user_id') . '%');
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
                $map['TYPE'] = 1;
                // $map['BEGIN_DATE'] = array('between', [date('Y-m-') . '01', date('Y-m-') . '31']);
                $weekPlan = M('work_plan')->where($map)->select();
                foreach ($weekPlan as $k => $v) {
                    //$weekPlan[$k]['name'] = mb_substr($v['name'], 0, 18);
                    $con['PLAN_ID'] = $v['plan_id'];
                    $con['WRITER'] = session('user_id');
                    $process = M('work_detail')->where($con)->sum('PERCENT');
                    $count = M('work_detail')->where($con)->count();
                    $weekPlan[$k]['percent'] = round($process / $count, 0);
                }
                //当前用户全部的月计划记录数
                $map['TYPE'] = 2;
                // $map['BEGIN_DATE'] = array('between', [date('Y-m-') . '01', date('Y-m-') . '31']);
                $monthCount = M('work_plan')->where($map)->count();

                //当前用户全部的项目计划记录数
                $map['TYPE'] = 11;
                // $map['BEGIN_DATE'] = array('between', [date('Y-m-') . '01', date('Y-m-') . '31']);
                $projectCount = M('work_plan')->where($map)->count();

                //当前用户全部的年计划记录数
                $map['TYPE'] = 7;
                //  $map['BEGIN_DATE'] = array('between', [date('Y-') . '01-01', date('Y-') . '12-31']);
                $yearCount = M('work_plan')->where($map)->count();
            }
            //当前用户全部计划
            $plan = count($weekPlan) + $monthCount + $projectCount + $yearCount;
        }
        return $plan;
    }

    //取消关注
    public function cancelAtten() {
        $id = I('id');
        $users = M('work_plan')->where('PLAN_ID=' . $id)->getField('follow_user');
        $users = explode(',', $users);
        foreach ($users as $key => $row) {
            if ($row == session('user_id')) {
                unset($users[$key]);
            }
        }
        $data['FOLLOW_USER'] = implode(',', $users);
        $res = M('work_plan')->where('PLAN_ID=' . $id)->save($data);
        if ($res !== false) {
            $return = array('status' => 1, 'msg' => '取消成功');
        } else {
            $return = array('status' => 0, 'msg' => '取消失败');
        }
        $this->ajaxReturn($return);
    }

    //历史计划,type=''取进行中和已完结的计划
    public function historyList() {
        $month = I('month');
        $map['BEGIN_DATE'] = array('between', [$month . '-01', $month . '-31']);

        //当前用户角色排序号
        $no = $this->privNo;
        if ($no < 40) {
            if ($no > 2) {
                $where['TO_ID'] = array('like', '%' . session('dept_id') . '%');
                $depts = array(explode(',', rtrim(session('dept_id_other'), ',')));
                if (!empty($depts[0][0])) {
                    foreach ($depts[0] as $key => $row) {
                        $where['TO_ID'] = array('like', '%' . $row . '%');
                    }
                    $where['_logic'] = 'or';
                    $map['_complex'] = $where;
                } else {
                    $map['TO_ID'] = $where['TO_ID'];
                }
            }
        } else {
            $where['executor'] = array('like', '%' . session('user_id') . '%');
            $where['MANAGER'] = array('like', '%' . session('user_id') . '%');
            $where['PARTICIPATOR'] = array('like', '%' . session('user_id') . '%');
            $where['CREATOR'] = session('user_id');
            $where['TO_PERSON_ID'] = array('like', '%' . session('user_id') . '%');
            $where['OPINION_LEADER'] = array('like', '%' . session('user_id') . '%');
//                $where['TO_ID'] = array('like', '%' . session('dept_id') . '%');
//                $where['TO_ID'] = array('like', '%' . session('dept_id_other') . '%');
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        }
        $limit = $this->limit;
        $lists = $this->getPlanData('', $limit, $map);

        foreach ($lists as $key => $row) {
            //获取负责人头像
            if (strpos($row['manager'], ',') !== false) {
                $row['manager'] = substr($row['manager'], 0, -1);
            }
            $lists[$key]['head'] = M('user')->where('USER_ID="' . $row['manager'] . '"')->getField('head');
            //截取过长的计划名称
            $len = strlen($row['name']);
            if ($len > 39) {
                $lists[$key]['sort'] = msubstr($row['name'], 0, 13);
            } else {
                $lists[$key]['sort'] = $row['name'];
            }

            //获取最新动态信息
            $dMap['PLAN_ID'] = $row['plan_id'];
            $info = M('work_detail')->where($dMap)->order('write_time desc')->limit(1)->getField('progress');
            $len = strlen($info);
            if ($len > 60) {
                $lists[$key]['info'] = msubstr($row['name'], 0, 20);
            } else {
                $lists[$key]['info'] = $info;
            }
        }

        //总条数
        $this->total = count($this->getPlanData('', 0, $map));

        $this->lists = $lists;
        $this->type = I('type');
        $this->month = $month;
        $this->display('lists');
    }

    //删除本人进度或批注
    public function delDetail() {
        $id = I('id');
        $dept = I('dept');
        $cType = I('cType');

        $row = M('work_detail')->where('DETAIL_ID=' . $id)->find();

        //删除移动端附件
        if ($row['uploads_url']) {
            $urls = explode(';', rtrim($row['uploads_url'], ';'));
            foreach ($urls as $url) {
                @unlink('.' . $url);
            }
        }
        //删除PC端附件
        if ($row['attachment_id']) {
            $pcurls = downloadFile($row['attachment_id'], $row['attachment_name'], 'work_plan');
            foreach ($pcurls as $pcurl) {
                @unlink($pcurl['url']);
            }
        }

        $res = M('work_detail')->where('DETAIL_ID=' . $id)->delete();
        if ($res !== false) {
            if ($row['type_flag'] == 0) {
                //修改当前计划总进度
                $this->saveOnePercent($row['plan_id']);
            }
            $return['status'] = 1;
            $return['url'] = U('Plan/show', array('id' => $row['plan_id'], 'dept' => $dept, 'cType' => $cType));
        } else {
            $return['status'] = 0;
        }

        $this->ajaxReturn($return);
    }

    public function upload() {
        $this->upfile('./Public/Uploads/plan/');
    }

    //进度日志删除页
    public function showSchedule() {
        $id = I('id') ? I('id') : session('pcId');

        $map['PLAN_ID'] = $id;
        $info = M('work_plan')->where($map)->find();
        $map['WRITER'] = array('like', '%' . session('user_id') . '%');
        $info['detail'] = M('work_detail')->where($map)->order('WRITE_TIME DESC')->select();
        if ($info['detail']) {
            foreach ($info['detail'] as $key => $row) {
                $info['detail'][$key]['formatTime'] = strtotime($row['write_time']);
                $info['detail'][$key]['self'] = session('user_id');     //本人
                //判断当前进度中是否有附件
                if ($row['attachment_name']) {
                    $info['detail'][$key]['file'] = 1;
                    $dUploads = downloadFile($row['attachment_id'], $row['attachment_name'], 'work_plan', $row['uploads'], $row['uploads_url']);
                }
                if ($row['uploads']) {
                    $names = explode(';', rtrim($row['uploads'], ';'));
                    $urls = explode(';', rtrim($row['uploads_url'], ';'));
                    for ($i = 0; $i < count($urls); $i++) {
                        $tmpArr = [];
                        if ($urls[$i]) {
                            if ($dUploads) {
                                $tmpArr['name'] = $names[$i];
                                $tmpArr['url'] = $urls[$i];
                                $info['detail'][$key]['file'] = 1;  //判断是否有附件
                                array_push($dUploads, $tmpArr);
                            } else {
                                $dUploads[$i]['name'] = $names[$i];
                                $dUploads[$i]['url'] = $urls[$i];
                                $info['detail'][$key]['file'] = 1;  //判断是否有附件
                            }
                        }
                    }
                }
            }

            $picArr = ['png', 'jpg', 'jpeg', 'psd', 'bmp', 'gif'];
            foreach ($dUploads as $key => $row) {
                $ext = end(explode('.', $row['name']));
                $dUploads[$key]['is_pic'] = in_array($ext, $picArr) ? 1 : 0;
            }
        }
//        echo '<pre>',print_r($info);die;
        $this->plan = $info;
        $this->dept = I('dept');
        $this->cType = I('cType');
        $this->display();
    }
    
    //获取子分类数据
    public function getChildType() {
        $id = I('id');
        $map['pid'] = $id;
        $map['user_id'] = session('user_id');
        $data = M('plan_type')->where($map)->select();
        $this->ajaxReturn($data);
    }

}
